package com.bestcem.xm.wallet.grpc.client;

import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.wallet.grpc.client.converter.WalletBpWechatConvert;
import com.bestcem.xm.wallet.grpc.client.dto.GenerateMiniProgramUrlSchemeDTO;
import com.bestcem.xm.wechat.grpc.v1.services.BpWechatServiceGrpc;
import com.bestcem.xm.wechat.grpc.v1.services.GenerateMiniProgramUrlSchemeRequest;
import com.bestcem.xm.wechat.grpc.v1.services.GenerateMiniProgramUrlSchemeResponse;
import com.zy.dp.proto.base.v1.Code;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 提供给微信的服务
 *
 * @author wangyunyun <yunyun.wang@idiaoyan.com>
 * @version v1.0
 * @date 2022/5/20 17:39
 */
@Slf4j
@Service("walletBpWechatGrpcService")
public class BpWechatGrpcService {

    @GrpcClient(GrpcClientNames.XM)
    private BpWechatServiceGrpc.BpWechatServiceBlockingStub stub;

    @Resource
    private WalletBpWechatConvert walletBpWechatConvert;

    /**
     * 生成微信小程序唤起链接
     *
     * @param generateMiniProgramUrlSchemeDTO 生成微信小程序唤起链接dto
     * @return String 微信小程序唤起链接
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/5/20 17:57
     */
    public String generateMiniProgramUrlScheme(GenerateMiniProgramUrlSchemeDTO generateMiniProgramUrlSchemeDTO) {
        // 设置请求参数
        GenerateMiniProgramUrlSchemeRequest request = walletBpWechatConvert.dto2GenerateMiniProgramUrlSchemeGrpc(generateMiniProgramUrlSchemeDTO);
        // 请求
        GenerateMiniProgramUrlSchemeResponse response = null;
        try {
            response = stub.generateMiniProgramUrlScheme(request);
        } catch (Exception e) {
            log.error("生成微信小程序唤起链接。请求失败", e);
        }
        // 返回值处理
        if (response != null && Code.OK_VALUE == response.getStatus().getCodeValue()) {
            if (log.isInfoEnabled()) {
                log.info("生成微信小程序唤起链接。response:{}", response.toString());
            }
            return response.getOpenLink();
        } else {
            log.error("生成微信小程序唤起链接。请求失败, response:{}", response != null ? response.toString() : null);
        }
        return null;
    }

}
